package com.basejace.system.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.basejace.common.model.PubDepartment;
import com.basejace.common.model.PubUser;
import com.basejace.common.model.PubUserdepartmentRela;
import com.basejace.core.R;
import com.basejace.core.base.BaseController;
import com.basejace.core.model.PageBootstrapTable;
import com.basejace.core.sequence.Sequence;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class DepartmentController extends BaseController {

	public DepartmentController(){
		setModelClass(PubDepartment.class);
	}
	
	public void main(){
		render("main.jsp");
	}
	
	public void show() {
		render("tree.jsp");
	}
	
	public void showUser() {
		setAttr("dptid",getPara("dptid"));
		render("userlist.jsp");
	}
	
	public void addUser() {
		Long dptid = getParaToLong("dptid");
		PubDepartment model = PubDepartment.dao.findById(dptid);
		setAttr("department", model);
		
		setAttr("userList", PubUser.dao.find("select userid,username,mobileno from pub_user where state=1"));
		setAttr("pagetitle", "新增部门员工");
		setAttr(R.Key.IS_NEW, R.Const.TRUE);
		setAttr(R.Key.IS_EDIT, R.Const.TRUE);
		render("usercontent.jsp");
	}
	public void listUser(){
		String username = getPara("username");
		String mobileno = getPara("mobileno");
		Long dptid = getParaToLong("dptid");
		
		String sqlExceptSelect = "from pub_user a, pub_userdepartment_rela b where a.userid=b.userid ";
		List sqlCondition = new ArrayList();
		if (StrKit.notBlank(username)) {
			sqlExceptSelect += "and a.username like ? ";
			sqlCondition.add("%" + username + "%");
		}
		if (StrKit.notBlank(mobileno)) {
			sqlExceptSelect += "and a.mobileno like ? ";
			sqlCondition.add("%" + mobileno + "%");
		}
		String userids = null;
		if (dptid != null) {
			sqlExceptSelect += "and b.departmentid = ? ";
			sqlCondition.add(dptid);
		}

		int offset = getParaToInt("offset");
		int limit = getParaToInt("limit");
		int pageNumber = (offset) / limit + 1;
		
		Page<Record> page = Db.paginate(pageNumber, limit, "select a.* ", sqlExceptSelect , sqlCondition.toArray());
		
		List<Record> list = page.getList();
		List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Record object = (Record) iterator.next();
			rows.add(object.getColumns());
		}
		
		PageBootstrapTable p = new PageBootstrapTable();
		p.setTotal(page.getTotalRow());
		p.setPageSize(page.getPageSize());
		p.setPageNumber(page.getPageNumber());
		p.setRows(rows);
		
		renderJson(p);
	}
	
	@Before(Tx.class)
	public void deleteUser() {
		//重新设点modelclass用来解析PK
		setModelClass(PubUserdepartmentRela.class);
		try {
			Object[] primaryKeys = getPK(getPara(R.Key.PK)); //可能有多组主键
			for (int i=0; i<primaryKeys.length; i++) {
				if (primaryKeys[i] instanceof Object[])
					this.getModelEntity().deleteById((Object[])primaryKeys[i]);
				else
					this.getModelEntity().deleteById(primaryKeys[i]);
//			或者使用下面这句
//			Db.deleteById(getTableName(getModelClass()), getTablePrimaryKey(getModelClass()), primaryKeys[i]);
			}
			setAttr(MSG, "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			setAttr(MSG, "删除失败："+ e.getMessage());
		}
		render("userlist.jsp");
	}
	
	@Before(Tx.class)
	public void saveUserDepartmentRela() {
		Map<String,String[]> str = getParaMap();
		String[] useridArray = str.get("userdepartmentRela.userid");
		Long dptid = getParaToLong("userdepartmentRela.departmentid");
		
		setModelClass(PubUserdepartmentRela.class);
		String selectUserid = "";
		try {
			PubDepartment model = PubDepartment.dao.findById(dptid);
			setAttr("department", model);
			
			for( String userid : useridArray) {
				new PubUserdepartmentRela().setDepartmentid(dptid).setUserid(Long.parseLong(userid)).save();
				selectUserid += "," + userid;
			}
			//查询部门信息
			setAttr(MSG, "新增成功");
		} catch (Exception e) {
			e.printStackTrace();
			setAttr(MSG, "保存失败：" + e.getMessage());
//			render("usercontent.jsp");
//			return;
		}
		
		//查询用户信息
		setAttr("userList", PubUser.dao.find("select userid,username,mobileno from pub_user where state=1"));
		
		setAttr("selectUserid", selectUserid.length() == 0 ? "" : selectUserid.substring(1));
		setAttr("pagetitle", "新增部门员工");
		this.setAttr(R.Key.IS_EDIT, R.Const.FALSE);
		this.setAttr(R.Key.IS_NEW, R.Const.FALSE);
		render("usercontent.jsp");
	}
	public void tree() {
		List<PubDepartment> department = PubDepartment.dao.find("select * from pub_department");
		JSONArray ao = new JSONArray();
		for (int i = 0; i < department.size(); i++) {
			JSONObject obj = new JSONObject();
			obj.put("id", department.get(i).getDptid());
			Long pid = department.get(i).getDptpid();
			obj.put("parent", pid == -1L ? "#" : pid.toString());
			obj.put("text", department.get(i).getDptname());
			//额外的参数可以设置的到li标签的属性里面
//			JSONObject li_attr = new JSONObject();
//			li_attr.put("fixed", department.get(i).getFixed());
//			obj.put("li_attr", li_attr);
			/*if (controls.get(i).getControlid().equals("00")) {
				Map<String,Object> openstate = new HashMap<String,Object>();
				openstate.put("opened", true);
				obj.put("state", new JSONObject(openstate));
			}*/
			
			obj.put("icon", "fa fa-file icon-state-warning icon-lg");
//			if (1 == department.get(i).getGrouptype()) {
//				obj.put("icon", "fa fa-folder icon-state-warning icon-lg");
//			} else if (2 == department.get(i).getGrouptype()) {
//				obj.put("icon", "fa fa-file icon-state-warning icon-lg");
//			} 
			ao.add(obj);
		}
		
		renderJson(ao);
	}
	
	
	public void beforeAdd() throws Exception {
		Long dptid = getParaToLong("dptid");
		Long nowDptid = Sequence.getSequence(); 
		this.getModelEntity().set("dptid", nowDptid);
		this.getModelEntity().set("dptpid", dptid);
		setAttr(this.getModelSimpleName(), this.getModelEntity());
	}
	
	@Before(Tx.class)
	public void delete () {
		try {
			this.beforeDelete();
			Object[] primaryKeys = getPK(getPara(R.Key.PK)); //可能有多组主键
			for (int i=0; i<primaryKeys.length; i++) {
				this.getModelEntity().deleteById(primaryKeys[i]);
//				或者使用下面这句
//				Db.deleteById(getTableName(getModelClass()), getTablePrimaryKey(getModelClass()), primaryKeys[i]);
			}
			this.afterDelete();
		} catch (Exception e) {
			e.printStackTrace();
			setAttr("message", "删除失败：" + e.getMessage());
		}
		setAttr(MSG, "删除成功");
		render("tree.jsp");
	}
}
